import util from "../../common/js/util.js";
var app = getApp();
let baseObj = {
  category_index: 0,

}
Component({
  mixins: [],
  data: {
    show: false,
    type: 0,// 1审批人 2 抄送人
    index: 0,
    searchList: util.copy(baseObj),
    categoryList: [],
    openData: {},
    edit_type:1,//部分编辑 1 编辑所有2
    move:true,
    disabled:false
  },
  props: {
    multiple: true,
    checkStaffList: "",//英文逗号隔开的字符串
    disStaffList: "",
    onPass: function onPass(e) { },
    onClose: function onClose(e) { }
  },
  didMount() {
    this.setData({
      disabled:true
    })
    this.getCategoryList()
  },
  didUpdate() {
    // this.setData({
    //   multiple: this.props.multiple
    // })
  },
  didUnmount() { },
  methods: {
    getCategoryList() {
      let api = "/YhERP/category/json/list"
      app.$post(api, { currentPage: 1, showCount: 50 }).then(res => {
        if (res.is == 1) {
          this.setData({
            categoryList: res.data.dataList
          })
        } else {
          util.message(res.msg)
        }
      })
    },
    closeMove() {
      this.setData({
        move: false
      })
    },
    openMove() {
      this.setData({
        move: true
      })
    },
    tableItemClick(e) {
      let value = e.currentTarget.dataset.value;
      dd.alert({
        content: value
      })
    },
    getMaterilDetail() {
      let MATERIAL_ID = this.data.searchList.MATERIAL_ID;
      if (MATERIAL_ID) {
        let api = "/YhERP/material/json/views"
        app.$post(api, { MATERIAL_ID }).then(res => {
          if (res.is == 1) {
            let CATEGORY_NAME = res.data.CATEGORY_NAME;
            let CATEGORY_ID = res.data.CATEGORY_ID;
            if (!this.data.searchList.CATEGORY_NAME) {
              this.setData({
                "searchList.CATEGORY_NAME": CATEGORY_NAME
              })
            }
            if (!this.data.searchList.CATEGORY_ID && CATEGORY_ID) {
              this.setData({
                "searchList.CATEGORY_ID": CATEGORY_ID
              })
            }
          } else {
            util.message(res.msg)
          }
        })
      }
    },
    addMaterilFn() {
      let api = "/YhERP/material/json/save";
      let list = {
        MATERIAL_NAME: this.data.searchList.MATERIAL_NAME,
        MODEL: this.data.searchList.MODEL,
        CATEGORY_NAME: this.data.searchList.CATEGORY_NAME,
        CATEGORY_ID: this.data.searchList.CATEGORY_ID
      }
      dd.showLoading({
        content: '数据提交中...',
      })
      app.$post(api, list).then(res => {
        if (res.is == 1) {
          let MATERIAL_ID = res.data;
          this.setData({
            "searchList.MATERIAL_ID": MATERIAL_ID
          })
          this.checkFileList();
          
        } else {
          util.message(res.msg)
        }
      })
    },
    checkFileList(){
      if(this.data.openData.action=="edit"){
        //检验文件进行文件上传
        if(util.isNotEmpty(this.data.searchList.file_list)){
          this.fileSubmit(this.data.searchList.PURCHASEORDER_ID);
        }else{
          this.onPass();
        }
      }else{
        this.onPass();
      }
    },
    onSelectPass(list) {
      //console.log(list);
      let node = list[0];

      this.setData({
        'searchList.CATEGORY_ID': node.CATEGORY_ID,
        'searchList.CATEGORY_NAME': node.CATEGORY_NAME,
        'searchList.MATERIAL_ID': node.MATERIAL_ID,
        'searchList.MATERIAL_NAME': node.MATERIAL_NAME,
        'searchList.METERING_NAME': node.METERING_NAME,
        'searchList.MODEL': node.MODEL,
        "searchList.FIXED_ASSETS": 0,
        "searchList.FIXED_ASSETS_VALUE": "否"
      })
      this.openMove();
    },
    complexChoose(e) {
      let key = e.currentTarget.dataset.key;

      let now = this.data.searchList.TIME5 ? this.data.searchList.TIME5 : util.getStringYMDByDate(new Date())
      let currentDate = this.data[`${key}`] ? this.data[`${key}`] : now;
 
      let that = this;
      dd.datePicker({
        format: 'yyyy-MM-dd',
        currentDate,
        success: (res) => {
          //console.log("--es.date", res.date);

          if(key=="searchList.TIME5"){
            that.setData({
              "searchList.TIME5_VALUE": util.dateStrParseSmpleStr(res.date)
            })
          }
          that.setData({
            [`${key}`]: res.date
          })
        },
      });
    },
    bindPickerChange(e) {
      let index = e.detail.value;
      let node = this.data.categoryList[index];
      let CATEGORY_NAME = node.CATEGORY_NAME;
      let CATEGORY_ID = node.CATEGORY_ID;
      this.setData({
        "searchList.CATEGORY_NAME": CATEGORY_NAME,
        "searchList.CATEGORY_ID": CATEGORY_ID
      })
    },
    //打开
    openFn(e) {
      // e={
      //   action:"edit",
      //   data:node,
      //   searchList:this.data.searchList
      //   status: 1  6,
      //   Role: Admin..,""
      // }

     //console.log("--初始数据",e);
     let edit_type=2;
     if(e.action=="edit"){

      //e.status==6&&!e.Role
      if(e.status==6){
        edit_type=1;//提起人编辑
      }
     }
     
      this.setData({
        openData: util.copy(e),
        edit_type
      })
      let searchList = e.searchList;

      let data = Object.assign(util.copy(baseObj), e.data);
      data.TIME5 = searchList.TIME1;
      data.PROJECT_ID = searchList.PROJECT_ID;
      data.PROJECT_NAME = searchList.PROJECT_NAME;
      data.PURCHASE_TYPE = searchList.PURCHASE_TYPE;
      let FIXED_ASSETS_VALUE="否";
      if(util.isNotEmpty(data.FIXED_ASSETS)){
        FIXED_ASSETS_VALUE = (data.FIXED_ASSETS == 0) ? "否" : "是";
      }
      data.FIXED_ASSETS_VALUE=FIXED_ASSETS_VALUE;
      if(e.status==6){
        if (util.isNotEmpty(data.APPROVAL_2)&&data.APPROVAL_2!="[]") {
          let list=[];
          if(Array.isArray(data.APPROVAL_2)){
            list=data.APPROVAL_2
          }else{
            list = JSON.parse(data.APPROVAL_2);
          }
          let APPROVAL_2_CN_NAME_ARR = [];
          for (let index = 0; index < list.length; index++) {
            let user_en_name = list[index];
            let user_cn_name = app.prototype.$USERNAME_MAP.get(user_en_name);
            if (util.isNotEmpty(user_cn_name)) {
              //  RECEIVERS.push(user_en_name);
              APPROVAL_2_CN_NAME_ARR.push(user_cn_name);
            };
          }
          data.APPROVAL_2=list;
          data.APPROVAL_2_CN_NAME = APPROVAL_2_CN_NAME_ARR.join(",");
        } else {
          data.APPROVAL_2 = [app.prototype.$SysUserName];
          data.APPROVAL_2_CN_NAME = app.prototype.$SysUserCnName;
        }
        data.APPROVAL_NOTE_1=0;
        data.APPROVAL_NOTE_1_VALUE="否";

      }

     // console.log("--商品数据:",data);
      if(data.PURCHASEORDER_ID){
        if(util.isEmpty(data.file_list)){
          this.fileList(data.PURCHASEORDER_ID);
        }
      }else{
        data.file_list=[];
      }
      if(util.isNotEmpty(data.TIME5)){
        data.TIME5_VALUE=util.dateStrParseSmpleStr(data.TIME5);
      }
      this.setData({
        show: true,
        searchList: data
      })
      this.getMaterilDetail();

      
      
    },
    switch2Change(e) {
      //console.log(e);
      let FIXED_ASSETS = 0, FIXED_ASSETS_VALUE = "否";
      if (e.detail.value) {
        FIXED_ASSETS = 1;
        FIXED_ASSETS_VALUE = "是"
      } else {
        FIXED_ASSETS = 0;
      }
      this.setData({
        "searchList.FIXED_ASSETS": FIXED_ASSETS,
        "searchList.FIXED_ASSETS_VALUE": FIXED_ASSETS_VALUE
      })
    },
    switchPriceChange(e) {
      //console.log(e);
      let APPROVAL_NOTE_1 = 0, APPROVAL_NOTE_1_VALUE = "否";
      if (e.detail.value) {
        APPROVAL_NOTE_1 = 1;
        APPROVAL_NOTE_1_VALUE = "是"
      } else {
        APPROVAL_NOTE_1 = 0;
      }
      this.setData({
        "searchList.APPROVAL_NOTE_1": APPROVAL_NOTE_1,
        "searchList.APPROVAL_NOTE_1_VALUE": APPROVAL_NOTE_1_VALUE
      })
    },
    onReset() {
      this.setData({
        searchList: util.copy(baseObj)
      })
    },
    //打开一个默认没有勾选的联系人
    openEmpty() {
      this.setData({
        show: true
      })
    },
    idsParseToApprovalRuleList(str = "") {
      let list = str.split(",");
      let RECEIVERS = [];
      for (let index = 0; index < list.length; index++) {
        let user_en_name = list[index];
        let user_cn_name = app.prototype.$USERNAME_MAP.get(user_en_name);
        if (util.isNotEmpty(user_cn_name)) {
          let json = {
            UserName: user_en_name,
            UserCnName: user_cn_name,
            name: user_cn_name
          }
          RECEIVERS.push(json);
        };
      }
      return RECEIVERS;
    },
    onPass() {
      dd.hideLoading();
      
      this.props.onPass(this.data.searchList);
      this.onCloseFn();
    },

    onCloseFn() {
      this.setData({
        show: false
      });
      this.props.onClose();
      // console.log(this.data.show);

      // this.onReset();
    },
    bindKeyInput(e) {
      let key = e.currentTarget.dataset.key;
      util.debounce(() => {
        this.setData({
          [`${key}`]: e.detail.value,
        });
      }, 300);

    },
    bindPriceKeyInput(e) {
      let key = e.currentTarget.dataset.key;
      let value = e.detail.value;
      let WAREHOUSING = "";
      if (!isNaN(value)) {
        let NUM = this.data.searchList.NUM;
        WAREHOUSING = (Number(NUM) * Number(value)).toFixed(2)
        util.debounce(() => {
          this.setData({
            'searchList.WAREHOUSING': WAREHOUSING,
            [`${key}`]: value,
          });
        }, 300);
      }
    },
    onPassIndexList(list) {
      let RECEIVERS = Array.isArray(this.data.searchList.APPROVAL_2)?this.data.searchList.APPROVAL_2:[], RECEIVER_CN_S =  this.data.searchList.APPROVAL_2_CN_NAME.split(",");
      for (let index = 0; index < list.length; index++) {
        let user_en_name = list[index];
        let user_cn_name = app.prototype.$USERNAME_MAP.get(user_en_name);
        if (util.isNotEmpty(user_cn_name)) {
          RECEIVERS.push(user_en_name);
          RECEIVER_CN_S.push(user_cn_name);
        };
      }
      this.setData({
        "searchList.APPROVAL_2_CN_NAME": RECEIVER_CN_S.join(","),
        "searchList.APPROVAL_2": RECEIVERS
      })
    },
    complexPeopleChoose(e) {
      let APPROVAL_2=Array.isArray(this.data.searchList.APPROVAL_2)?this.data.searchList.APPROVAL_2.join(","):[] ;
      this.index_list.openDisFn(APPROVAL_2);
    },
    complexImgChoose(e) {
      //  let type = e.currentTarget.dataset.type;
      let type = "file_list";
      // console.log(type);
      let _this = this;
      dd.chooseImage({
        count:3,
        success: (res) => {
          //console.log(res);
          try {
            let imgArr = [];
            for (let index = 0; index < res.filePaths.length; index++) {
              let url = res.filePaths[index];
              let arr = url.split("https://resource/");
              let name = arr[1];
              let json = {
                status: "ready",
                url, name
              }
              imgArr.push(json)
            }
            // console.log(type);
           // console.log(imgArr);
            this.setData({
              [`searchList.${type}`]: this.data.searchList[type].concat(imgArr)
            })
          } catch (e) {
            console.log(e);
          }
        },
        fail: (err) => {
          // #ifdef MP
          dd.getSetting({
            success: (res) => {
              let authStatus = res.authSetting['scope.album'];
              if (!authStatus) {
                dd.showModal({
                  title: '授权失败',
                  content: 'Hello dd-app需要从您的相册获取图片，请在设置界面打开相关权限',
                  success: (res) => {
                    if (res.confirm) {
                      dd.openSetting()
                    }
                  }
                })
              }
            }
          })
          // #endif
        }
      })
    },
    fileDelete(e) {
      let type = "file_list";
      let status = e.currentTarget.dataset.status;
      let ENCLOSURE_ID = e.currentTarget.dataset.ENCLOSURE_ID;
      let searchList = this.data.searchList;
      if (status == "ready") {
        for (let i in searchList[type]) {
          if (searchList[type][i].lastModified == e.lastModified) {
            searchList[type].splice(i, 1);
          };
        };
        this.setData({
          searchList
        })
      } else {
        app.$post("/YhERP/enclosure/delete", {
          ENCLOSURE_ID
        }).then(res => {
          if (res.is == 1) {
            util.message("删除成功");
            for (let i in searchList[type]) {
              if (searchList[type][i].lastModified == e.lastModified) {
                searchList[type].splice(i, 1);
              };
            };
            this.setData({
              searchList
            })
            this.fileList(searchList.PURCHASEORDER_ID);
          };
        });
      }
    },
    fileView(e) {
      let url = e.currentTarget.dataset.url;
      console.log(url);
      app.fileView(url);
      // dd.previewImage({
      //   current: 2,
      //   urls: [
      //     url
      //   ],
      // });
    },
    fileList(id) {
      app.$post("/YhERP/enclosure/json/enclosureList", {
        TYPE_NAME: 'PurchaseOrderEnclosure',
        PID: id
      }).then(res => {

        if (res.is == 1) {
          //this.FILETRUE = true;
          for (let i in res.data) {
            res.data[i].extname = "text";
            res.data[i].name = res.data[i].FILE_NAME;
            res.data[i].url = app.prototype.$urls + res.data[i].PATH;
          };
          
          this.setData({
            'searchList.file_list': res.data
          })
        } else {
          this.setData({
            "searchList.file_list": []
          })
        }
      }).catch(err => {
        // console.log(err);
        if (err.msg == "列表为空！") {
          this.setData({
            "searchList.file_list": []
          })
        }
      });
    },
    submitFn(){
      
      
    },
    fileSubmit(id) {

      let name="file_list";
      let up=0;
      dd.showLoading({
        content: '数据提交中...',
      })
      for (let i = 0; i < this.data.searchList[name].length; i++) {
        if (this.data.searchList[name][i].status == "ready") {
          up=up+1;
          let data = {
            TYPE: 1,
            PID: id,
            TYPE_NAME: "PurchaseOrderEnclosure",
            Token: app.prototype.$Token,
            // file: this.data.searchList[name][i],
            url: this.data.searchList[name][i].url,
            FILE_NAME: this.data.searchList[name][i].name,
          };
          app.$postFile(data).then(res => {
            this.setData({
              [`searchList[${name}][${i}].status`]:"success"
            })
            if (this.data.searchList[name].length - 1 == i) {
              setTimeout(() => {
                this.setData({
                  "searchList.file_list_load":1
                })
                
                dd.showToast({
                  title: "提交成功",
                  duration: 1000
                });
                this.onPass()
              }, 200);
            };
          });
        };
      };
      if(up==0){
        dd.showToast({
          title: "提交成功",
          duration: 1000
        });
        this.onPass()
      }
    },
    select_category_list(ref) {
      this.select_category_list = ref;
    },
    addTableItem() {

      this.select_category_list.openFn(this.data.searchList);
      this.closeMove();
    },
    pass() {
      if (util.isEmpty(this.data.searchList.MATERIAL_NAME)) {
        util.message("请选择商品");
        return false;
      }
      if (util.isEmpty(this.data.searchList.MODEL)) {
        util.message("请输入规格");
        return false;
      }
      if (util.isEmpty(this.data.searchList.TIME5)) {
        util.message("请选择预计使用时间");
        return false;
      }
      if (util.isEmpty(this.data.searchList.NUM)) {
        util.message("请输入数量");
        return false;
      }
      if (util.isEmpty(this.data.searchList.METERING_NAME)) {
        util.message("请输入单位");
        return false;
      }
      if (this.data.searchList.PURCHASE_TYPE=='2'&&util.isEmpty(this.data.searchList.ESTIMATED_PRICE)) {
        util.message("请输入预估单价");
        return false;
      }
      
      if(this.data.openData.status==6){
        if (util.isEmpty(this.data.searchList.ACTUAL_SUPPLIER)) {
          util.message("请输入实际采购供应商");
          return false;
        }
        if (util.isEmpty(this.data.searchList.APPROVAL_1)) {
          util.message("请输入实际供应商联系方式");
          return false;
        }
        if (util.isEmpty(this.data.searchList.SIMPLE_PRICE)) {
          util.message("请输入采购单价");
          return false;
        }
        if (util.isEmpty(this.data.searchList.WAREHOUSING)) {
          util.message("请输入采购总价");
          return false;
        }
      }

      //  console.log(this.data.searchList);
      if (util.isEmpty(this.data.searchList.MATERIAL_ID)) {
        this.addMaterilFn();
      } else {
        this.checkFileList();
      }

    },
    index_list(ref) {
      this.index_list = ref;
    }
  }

});
